<?php
namespace Components\Account\User\Address;

class Service {
	private $models = [];
	public function getModelsById($id = null) {
		if(is_null($id)) {
			return $this -> models;
		}

		if(!is_numeric($id) || $id <= 0) {
			return false;
		}

		if(isset($this -> models[$id]) && !empty($this -> models[$id]) && is_object($this -> models[$id])) {
			return $this -> models[$id];
		}

		$model = $this -> findFirstById($id);
		if($model['code'] != 0) {
			return false;
		}

		return $this -> models[$id] = $model['user_address'];
	}

	public function find($parameters = []) {
		$model = Model::find($parameters);
		if(!$model -> valid()) {
			return ['code' => -1, 'message' => '数据不存在或已删除'];
		}

		return ['code' => 0, 'user_address'=>$model];
	}

	public function findFirst($parameters = []) {
		$model = Model::findFirst($parameters);
		if(!$model) {
			return ['code' => -1, 'message' => '数据不存在或已删除'];
		}

		return ['code' => 0, 'user_address'=>$model];
	}

	public function findFirstById($id) {
		if($id <= 0) {
			return ['code' => -1, 'message' => '数据不存在或已删除'];
		}

		return $this -> findFirst(['address_id = ' . $id]);
	}

	public function create($data) {
		$model = new Model($data);
		if(!$model -> create()) {
			$messages = $model -> getMessages();
			return ['code' => -1, 'message' => $messages[0] -> getMessage()];
		}

		return ['code' => 0, 'user_address'=>$model];
	}

	public function update($id, $data) {
		if(!$this -> getModelsById($id)) {
			return ['code' => -1, 'message'=>'数据不存在或已删除'];
		}

		if(!$this -> models[$id] -> update($data)) {
			$messages = $this -> models[$id] -> getMessages();
			return ['code' => -1, 'message' => $messages[0] -> getMessage()];
		}

		return ['code' => 0, 'user_address'=>$this -> models[$id]];
	}

	public function delete($id) {
		if(!$this -> getModelsById($id)) {
			return ['code' => -1, 'message'=>'数据不存在或已删除'];
		}

		if(!$this -> models[$id] -> delete()) {
			$messages = $this -> models[$id] -> getMessages();
			return ['code' => -1, 'message' => $messages[0] -> getMessage()];
		}

		return ['code' => 0, 'user_address'=>$this -> models[$id]];
	}
}
